'use strict';

angular.module('sessions').controller('SessionsController',  ['$scope', '$stateParams', '$http' ,'$location', 'Authentication', 'Sessions','Profile',
	function($scope, $stateParams,$http, $location, Authentication, Sessions,Profile) {
		$scope.authentication = Authentication;
		$scope.today = new Date();

		/*
		* Initialize the create session form
		* - Populates the groups dropdown
		* - Populates presenters on group change
		* - Set selected presenters
		*/
		$scope.initCreateSessionForm=function(){
			$scope.groupMembers=[];
			$scope.presenters = [];
			$scope.durations =[0.1,0.2,0.3,4,5,6,7,8,9];

			Profile.allGroups().then(function(groups){
				$scope.activeGroups =groups;

			});
			$scope.groupChnaged=function(selectedValue) {
				if (selectedValue !== null && angular.isDefined(selectedValue)) {
					$scope.presenters = [];
					Profile.getUsersOfGroup(selectedValue.id).then(function (usersOfSelectedGroup) {
						$scope.groupMembers = usersOfSelectedGroup;
					});
				}else{
					$scope.groupMembers=[];
					$scope.presenters = [];
				}
			};
			$scope.presenterSelection=function(selectedUser){
				var idx = $scope.presenters.indexOf(selectedUser);
				// is currently selected
				if (idx > -1) {
					$scope.presenters.splice(idx, 1);
				}
				// is newly selected
				else {
					$scope.presenters.push(selectedUser);
				}
			};


			$scope.openSchedulesOnDatePicker = function($event) {
				$event.preventDefault();
				$event.stopPropagation();

				$scope.schedulesOnDatePicker = true;
			};
			$scope.create = function() {
				var presenters  = this.presenters.map(function(item){
					return {userId:item};
				});
				var scheduledOn = new Date();
				var session = new Sessions({
					title: this.title,
					content: this.content,
					presenters:presenters,
					duration:this.duration,
					group:this.group.id,
					scheduledOn:scheduledOn
				});
				session.$save(function(response) {
					$location.path('sessions/' + response._id);
					$scope.title = '';
					$scope.content = '';
					$scope.presenters= [];
				}, function(errorResponse) {
					$scope.error = errorResponse.data.message;
				});
			};

		};

		$scope.initSessionView=function(){
			$scope.hideStartSession = true;

			$scope.showSessionStartForm=function(){
				$scope.hideStartSession = !$scope.hideStartSession;
				if(!$scope.hideStartSession){
					// render user group;
					Profile.getUsersOfGroup($scope.session.group).then(function (usersOfSelectedGroup) {
						$scope.groupMembers = usersOfSelectedGroup;
					});
				}
			};
			$scope.audienceSelection=function(selectedUser){
				var idx = $scope.session.audience.indexOf(selectedUser);
				// is currently selected
				if (idx > -1) {
					$scope.session.audience.splice(idx, 1);
				}
				// is newly selected
				else {
					$scope.session.audience.push(selectedUser);
				}
			};

			$scope.startSession=function(){
				$http.post('/sessions/'+$scope.session._id, {
					startsOn:new Date(),
					audience: $scope.session.audience

				}).success(function(response) {
					window.location.reload(true);
					//$location.path('sessions/' + $scope.session._id);
				}).error(function(response) {
					$scope.error = response.message;
				});
			};
			$scope.bindPresenterAndRating=function(presenters){
				$scope.presenters =  presenters;
				Profile.populateUsersDisplayName($scope.presenters,'userId').then(function(presnters){
					$scope.presenters = presnters;
					$scope.presenters.forEach(function(presenter){
						presenter.rate=0;
						presenter.rating.forEach(function(rating){
							presenter.rate += rating.rating; // computed rating
						});
						presenter.rate = presenter.rate/presenter.rating.length;
					});
				});
			};

			$scope.ratePresenter= function(presenterId,rating){
				if(angular.isNumber(rating)&& $scope.session.audience.indexOf($scope.authentication.user._id)>0) {
					$http.post('/sessions/' + $scope.session._id + '/rateSession', {
						presenterId: presenterId,
						rating: rating
					}).success(function (response) {
						// If successful show success message and reset rating
						$scope.success = true;
						$scope.bindPresenterAndRating(response.presenters);
						//$scope.user = Authentication.user = response;
					}).error(function (response) {
						$scope.error = response.message;
					});
				}
			};
			$scope.findOne = function() {
				$scope.session = Sessions.get({
					sessionId: $stateParams.sessionId
				},function(response){
					$scope.bindPresenterAndRating(response.presenters);
				});
			};
			$scope.removeSession=function(){
				$scope.session.$remove(function() {
					$location.path('sessions');
				});
			};

			$scope.findOne();
		};



		$scope.find = function() {
			$scope.sessions = Sessions.query(function(sessions) {
				var presenters =[];
				sessions.forEach(function(sess){
					presenters = presenters.concat(
						sess.presenters.map(function(presenter){
							return presenter._id;
						})
					);
				});
				// Profile.getUsersForIds(presenters) is only to club all the presenters
				// and make a single service request to fetch all users at once
				Profile.getUsersForIds(presenters.filter(function(n){ return n !== undefined; })).then(function(){
					sessions.forEach(function(sess){
						Profile.populateUsersDisplayName(sess.presenters,'userId').then(function(presnters){
							sess.presentersToShow = presnters.filter(function(n){ return n.displayName !== undefined; }).map(function(prentr){
								return prentr.displayName;
							}).join(', ');
						});
					});

				});
			});
		};






	}
]);
